﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
using com.IronOne.BoardPACWinApp.Common;
using com.IronOne.BoardPACWinApp.Helpers;
using com.IronOne.BoardPACWinAppBO.Category;
using com.IronOne.BoardPACWinAppBO.General;
using com.IronOne.BoardPACWinAppBO.Paper;
using com.IronOne.BoardPACWinAppBO.Sync;
using com.IronOne.BoardPACWinAppService.Agenda;
using com.IronOne.BoardPACWinAppService.Category;
using com.IronOne.BoardPACWinAppUtil.Enums;
using com.IronOne.BoardPACWinAppUtil.Util;
using GalaSoft.MvvmLight.Messaging;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace com.IronOne.BoardPACWinApp.View.Page
{
    /// <summary>
    ///     A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class PastPapersSearchPage
    {
        public static CategoryModel GlobalCategorySelectedItem;
        public static SubCategoryModel GlobalSubCategorySelectedItem;
        public static List<PastPaperModel> GlobalPastPaperModels;
        public static PastPaperSearchModel GlobalPastPapersSearchModel;
        public static bool PreserveSearchResult;
        private IAgendaService _agendaService;
        private ICategoryService _categoryService;
        private IDialogService _dialogService;
        private int _globalCategoryId = -1;
        private List<CategoryModel> _globalCategoryList;
        private int _globalSubCategoryId = -1;
        private List<SubCategoryModel> _globalSubCategoryList;
        private INavigationService _navigationService;

        public PastPapersSearchPage()
        {
            InitializeComponent();
            NavigationHelper = new NavigationHelper(this);
            //this.navigationHelper.LoadState += navigationHelper_LoadState;
            //this.navigationHelper.SaveState += navigationHelper_SaveState;

            _navigationService = new NavigationService();
            _dialogService = new DialogService();
            _categoryService = new CategoryService();
            _agendaService = new AgendaService();

            PaperStatusCmb.ItemsSource = ApplicationConstants.PaperStatusCust;
        }

        /// <summary>
        ///     NavigationHelper is used on each page to aid in navigation and
        ///     process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper { get; private set; }

        protected override async void HandleMessages(NotificationMessage<MessageDataModel> mdm)
        {
            try
            {
                base.HandleMessages(mdm);
                await BasePage.GetInstance().HandleMessages(mdm);

                if (mdm.Notification.Equals(MessageCodes.SYNC_UPDATED_DATA))
                {
                    var sudm = (SyncUpdatedDataModel) mdm.Content.MessageData;
                    if (sudm.IsNewOrUpdatedCategories)
                    {
                        await PopulateCategoryListView();
                        return;
                    }

                    if (!sudm.IsNewOrUpdatedSubCategories) return;

                    #region GetSubCategoriesByCategoryId

                    var lhdm =
                        await
                            CommonHelper.GetInstance()
                                .RefereshSubCategoryListView(_categoryService, _globalCategoryId, _globalSubCategoryList,
                                    SubCategoryListView, GlobalSubCategorySelectedItem);
                    _globalSubCategoryList = lhdm.GlobalSubCategoryList;

                    #endregion
                }
            }
            catch (Exception)
            {
            }
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                base.OnNavigatedTo(e);
                NavigationHelper.OnNavigatedTo(e);

                PreserveSearchResult = false;

                await PopulateCategoryListView();

                if (GlobalPastPapersSearchModel != null)
                {
                    //TODO: fill text fiels
                    PaperNoTxt.Text = GlobalPastPapersSearchModel.PaperRefNo;
                    StartDateDatePicker.Date = GlobalPastPapersSearchModel.MeetingDateFrom ?? DateTime.Now;
                    EndDateDatePicker.Date = GlobalPastPapersSearchModel.MeetingDateTo ?? DateTime.Now;
                    KeywordTxt.Text = GlobalPastPapersSearchModel.KeyWord;

                    if (GlobalPastPapersSearchModel.PaperStatus != null)
                    {
                        PaperStatusCmb.SelectedIndex = GlobalPastPapersSearchModel.PaperStatusSelectedIndex;
                    }

                    StartDateChk.IsChecked = GlobalPastPapersSearchModel.StartDateChecked;
                    EndDateChk.IsChecked = GlobalPastPapersSearchModel.EndDateChecked;

                    //NOTE: If app is on narrow orientation and search results are there
                    //show it instead of search panel
                    if (Window.Current.Bounds.Width <= Utility.GetNarrowWidthSize())
                    {
                        NarrowWisthSetValues();
                    }
                }
                if (GlobalPastPaperModels != null)
                {
                    PastPapersGridView.DataContext = GlobalPastPaperModels;
                }
            }
            catch (Exception)
            {
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            try
            {
                base.OnNavigatedFrom(e);
                NavigationHelper.OnNavigatedFrom(e);

                if (!PreserveSearchResult)
                {
                    GlobalCategorySelectedItem = null;
                    _globalCategoryList = null;

                    GlobalSubCategorySelectedItem = null;
                    _globalSubCategoryList = null;

                    GlobalPastPaperModels = null;
                    GlobalPastPapersSearchModel = null;
                }
            }
            catch (Exception)
            {
            }
        }

        private async Task PopulateCategoryListView()
        {
            var helper =
                await
                    CommonHelper.GetInstance()
                        .PopulateCategoryListView(_globalCategoryList, _categoryService, GlobalCategorySelectedItem,
                            CategoryListView, _globalSubCategoryId, GlobalSubCategorySelectedItem);
            _globalCategoryList = helper.GlobalCategoryList;
            GlobalCategorySelectedItem = helper.GlobalCategorySelectedItem;
            _globalSubCategoryId = helper.GlobalSubCategoryId;
            GlobalSubCategorySelectedItem = helper.GlobalSubCategorySelectedItem;
        }

        private async void CategoryListViewSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                #region CommonCategoryListViewSelectionChanged

                var lhdm =
                    await
                        CommonHelper.GetInstance()
                            .CommonCategoryListViewSelectionChanged(CategoryListView, _categoryService,
                                SubCategoryListView, GlobalSubCategorySelectedItem);
                if (lhdm != null)
                {
                    GlobalCategorySelectedItem = lhdm.GlobalCategorySelectedItem;
                    _globalCategoryId = lhdm.GlobalCategoryId;
                    _globalSubCategoryList = lhdm.GlobalSubCategoryList;
                    GlobalSubCategorySelectedItem = lhdm.GlobalSubCategorySelectedItem;
                }

                #endregion
            }
            catch (Exception)
            {
            }
        }

        private void SubCategoryListViewSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                #region SubCategoryListViewSelectionChanged

                var lhdm = CommonHelper.GetInstance().CommonSubCategoryListViewSelectionChanged(SubCategoryListView);
                _globalSubCategoryId = lhdm.GlobalSubCategoryId;
                GlobalSubCategorySelectedItem = lhdm.GlobalSubCategorySelectedItem;

                #endregion
            }
            catch (Exception)
            {
            }
        }

        private void ClearAll_Btn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                PaperNoTxt.Text = "";
                StartDateDatePicker.Date = DateTimeOffset.Now;
                EndDateDatePicker.Date = DateTimeOffset.Now;
                KeywordTxt.Text = "";
                PaperStatusCmb.SelectedIndex = -1;
                CategoryListView.SelectedIndex = 0;

                StartDateChk.IsChecked = false;
                EndDateChk.IsChecked = false;

                NoResultLbl.Visibility = Visibility.Collapsed;
                SearchingLbl.Visibility = Visibility.Collapsed;
                SearchPgb.Visibility = Visibility.Collapsed;
                PastPapersGridView.DataContext = null;
            }
            catch (Exception)
            {
            }
        }

        private bool _isSerching;
        private async void Search_Btn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _isSerching = true;
                ClearAllBtn.IsEnabled = false;
                SearchBtn.IsEnabled = false;
                NoResultLbl.Visibility = Visibility.Collapsed;

                SearchingLbl.Visibility = Visibility.Visible;
                SearchPgb.Visibility = Visibility.Visible;

                if(Window.Current.Bounds.Width <= Utility.GetNarrowWidthSize())
                    SearchPgb2.Visibility = Visibility.Visible;
                
                PastPapersGridView.DataContext = null;

                int? categoryId = null;
                if (CategoryListView.SelectedIndex != -1 && CategoryListView.SelectedIndex != 0)
                {
                    var model = (CategoryModel) CategoryListView.SelectedItem;
                    if (model != null)
                        categoryId = model.CategoryId;
                }

                int? subCategoryId = null;
                if (SubCategoryListView.SelectedIndex != -1)
                {
                    var selectedItem = (SubCategoryModel) SubCategoryListView.SelectedItem;
                    if (selectedItem != null)
                        subCategoryId = selectedItem.SubCategoryId;
                }

                var paperNo = PaperNoTxt.Text.Trim();

                DateTime? startDate = null;
                if (StartDateDatePicker.IsEnabled)
                    startDate = StartDateDatePicker.Date.Date;

                DateTime? endDate = null;
                if (EndDateDatePicker.IsEnabled)
                    endDate = EndDateDatePicker.Date.Date;

                if (StartDateDatePicker.IsEnabled && EndDateDatePicker.IsEnabled)
                {
                    if (StartDateDatePicker.Date.Date > EndDateDatePicker.Date)
                    {
                        await _dialogService.ShowMessage("Start date should be earlier than the end date");
                        ClearAllBtn.IsEnabled = true;
                        SearchBtn.IsEnabled = true;
                        SearchingLbl.Visibility = Visibility.Collapsed;
                        SearchPgb.Visibility = Visibility.Collapsed;
                        return;
                    }
                }

                var keyword = KeywordTxt.Text.Trim();

                int? paperStatus = null;
                var paperStatusSelectedIndex = -1;
                if (PaperStatusCmb.SelectedItem != null)
                {
                    var tmpStats = PaperStatusCmb.SelectedItem.ToString();
                    paperStatusSelectedIndex = PaperStatusCmb.SelectedIndex;
                    paperStatus = (int) Enum.Parse(typeof (PaperStatusCust), tmpStats);
                }

                GlobalPastPapersSearchModel = new PastPaperSearchModel
                {
                    CategoryId = categoryId,
                    KeyWord = keyword,
                    MeetingDateFrom = startDate,
                    MeetingDateTo = endDate,
                    PaperRefNo = paperNo,
                    PaperStatus = paperStatus,
                    PaperStatusSelectedIndex = paperStatusSelectedIndex,
                    SubCategoryId = subCategoryId,
                    StartDateChecked = StartDateChk.IsChecked,
                    EndDateChecked = EndDateChk.IsChecked
                };

                await Task.Delay(5000);
                var rdm = await _agendaService.GetPastPapersSearchResults(GlobalPastPapersSearchModel);

                if (rdm.IsError)
                {
                    SearchPgb.Visibility = Visibility.Collapsed;
                    await _dialogService.ShowMessage(rdm.ErrorMessage);
                }
                else
                {
                    var ppm = (List<PastPaperModel>) rdm.Data;

                    if (ppm.Count <= 0)
                    {
                        NoResultLbl.Visibility = Visibility.Visible;
                    }

                    GlobalPastPaperModels = ppm;
                    PastPapersGridView.DataContext = ppm;
                }
            }
            catch (Exception)
            {
                NoResultLbl.Visibility = Visibility.Collapsed;
            }
            finally
            {
                _isSerching = false;
                if (Window.Current.Bounds.Width <= Utility.GetNarrowWidthSize())
                {
                    NarrowWisthSetValues();
                }

                ClearAllBtn.IsEnabled = true;
                SearchBtn.IsEnabled = true;
                SearchingLbl.Visibility = Visibility.Collapsed;
                SearchPgb.Visibility = Visibility.Collapsed;
                //NOTE: Used in the narrow orienatation
                SearchPgb2.Visibility = Visibility.Collapsed;
            }
        }

        private void NarrowWisthSetValues()
        {
            Grid.SetColumn(Grid2, 0);
            Grid.SetColumnSpan(Grid2, 26);
            Grid.SetRow(Grid2, 0);
            Grid.SetRowSpan(Grid2, 2);
            Grid2.Visibility = Visibility.Visible;
            Grid1.Visibility = Visibility.Collapsed;
        }

        private void NarrowBackButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Grid2.Visibility = Visibility.Collapsed;
                Grid1.Visibility = Visibility.Visible;
            }
            catch (Exception)
            {
            }
        }

        private void PageRoot_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            try
            {
                if (e.NewSize.Width <= Utility.GetNarrowWidthSize() && _isSerching)
                {
                    SearchPgb2.Visibility = Visibility.Visible;
                }
                else
                {
                    SearchPgb2.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception)
            {
            }
        }

        private void PastPapersGridViewSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                PreserveSearchResult = true;

                if (PastPapersGridView.SelectedIndex == -1)
                    return;

                var model = (PastPaperModel) PastPapersGridView.SelectedItem;
                if (model == null) return;

                var paper = new PaperModel
                {
                    Actions = model.AllowedActions,
                    Description = model.Description,
                    DocCreatedDateTime = model.DocCreatedDateTime,
                    DocName = model.DocName,
                    DocType = model.DocType,
                    PpDocTypeIconPath = model.DocTypeIconPath,
                    PpMeetingDateDisplay = model.MeetingDateDisplay,
                    PpMeetingSubCategory = model.MeetingSubCategory,
                    PaperId = model.PaperId,
                    PaperRefNo = model.PaperRefNo,
                    PaperStatus = (byte) model.PaperStatus,
                    PpPaperStatusValue = model.PaperStatusValue,
                    VersionInfo = model.SeVersion,
                    VersionId = model.VersionId
                };
                //paper. = model.Category;
                //paper. = model.FileExtension;
                //paper.UsersRestrictionStatus = model.IsRestricted;
                //paper. = model.MeetingDate;
                //paper. = model.MeetingId;
                //paper. = model.MeetingStatusValue;
                //paper. = model.MeetingType;

                var pModel = new List<PaperModel> {paper};
                _navigationService.NavigateTo(typeof (NewsAndShardDocsPage), pModel);
            }
            catch (Exception)
            {
            }
        }

        private void pageRoot_Unloaded(object sender, RoutedEventArgs e)
        {
            _navigationService = null;
            _dialogService = null;
            _categoryService = null;
            _agendaService = null;
        }

        #region StartDate

        private void StartDate_Chk_Checked(object sender, RoutedEventArgs e)
        {
            StartDateDatePicker.IsEnabled = true;
        }

        private void StartDate_Chk_Unchecked(object sender, RoutedEventArgs e)
        {
            StartDateDatePicker.IsEnabled = false;
        }

        private void StartDate_txt_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (StartDateChk.IsChecked != null && (bool) StartDateChk.IsChecked)
                StartDateChk.IsChecked = false;
            else
                StartDateChk.IsChecked = true;
        }

        #endregion

        #region EndDate

        private void EndDate_Chk_Checked(object sender, RoutedEventArgs e)
        {
            EndDateDatePicker.IsEnabled = true;
        }

        private void EndDate_Chk_Unchecked(object sender, RoutedEventArgs e)
        {
            EndDateDatePicker.IsEnabled = false;
        }

        private void EndDate_txt_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (EndDateChk.IsChecked != null && (bool) EndDateChk.IsChecked)
                EndDateChk.IsChecked = false;
            else
                EndDateChk.IsChecked = true;
        }

        #endregion

    }
}